package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wy.dto.GoodsAuctionDto;
import com.wy.entity.GoodsOrder;
import com.wy.entity.UserInfo;
import com.wy.mapper.*;
import com.wy.service.GoodsOrderService;
import com.wy.util.EmailSender;
import com.wy.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author:王渝
 * @Date: 2022/11/30  11:18
 * @Version 1.0
 */
@Slf4j
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    @Autowired
    private GoodsAuctionMapper goodsAuctionMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private GoodsDepositMapper goodsDepositMapper;

    @Autowired
    private EmailSender emailSender;

    private IdWorker idWorker= new IdWorker(1,1,1);

    @Transactional(rollbackFor = {})
    @Override
    public List<String>timedInsert() {

        //查询拍卖结束并且没有生成订单的商品
        List<GoodsOrder> goodsOrders = goodsInfoMapper.queryInfo();
       if(goodsOrders != null && goodsOrders.size() > 0){
           //保存id集合  修改auction中生成订单状态
           List<Long> goodsIds = new ArrayList<>();
           //存放用户id
           List<Long> userIds = new ArrayList<>();
           for (GoodsOrder goodsOrder : goodsOrders) {
               //填充字段
               goodsOrder.setOrderId(idWorker.nextId());
               goodsOrder.setCreateTime(LocalDateTime.now());
               goodsOrder.setUpdateTime(LocalDateTime.now());
               goodsIds.add(goodsOrder.getGoodsId());
               userIds.add(goodsOrder.getBuyerUserId());
           }
           //插入到order表中去
           goodsOrderMapper.insertBatch(goodsOrders);
           //修改生成订单状态
           goodsAuctionMapper.updateBatch(goodsIds);
           //查询用户邮箱
           List<String> list = userInfoMapper.queryEmail(userIds);

           return list;
       }
       return null;

    }

    @Transactional(rollbackFor = {})
    @Override
    public int timedChangeStatus() {
        int i = userInfoMapper.updateBreakCount();
        int i1 = goodsDepositMapper.updateDeductDeposit();
        int i2 = goodsOrderMapper.updateStatusByTime();
        return 0;
    }

    @Override
    public PageInfo<GoodsOrder> queryPageByUserId(int currentPage, int pageSize, Long userId, String status) {
        PageHelper.startPage(currentPage,pageSize);
        List<GoodsOrder> goodsOrders = goodsOrderMapper.queryAllByUserIdAndStatus(userId, status);
        PageInfo<GoodsOrder> goodsOrderPageInfo = new PageInfo<>(goodsOrders);
        return goodsOrderPageInfo;
    }

    @Override
    public PageInfo<GoodsOrder> queryPageByUserId2(int currentPage, int pageSize, Long userId,String  status) {
        PageHelper.startPage(currentPage,pageSize);
        List<GoodsOrder> goodsOrders = goodsOrderMapper.queryAllByUserIdAndStatus2(userId, status);
        PageInfo<GoodsOrder> goodsOrderPageInfo = new PageInfo<>(goodsOrders);
        return goodsOrderPageInfo;
    }


    @Override
    public PageInfo<GoodsOrder> queryPageBySellerId(int currentPage, int pageSize, Long userId) {
        PageHelper.startPage(currentPage,pageSize);
        List<GoodsOrder> goodsOrders = goodsOrderMapper.queryAllBySellerUserId(userId);
        PageInfo<GoodsOrder> goodsOrderPageInfo = new PageInfo<>(goodsOrders);
        return goodsOrderPageInfo;
    }

    @Override
    public PageInfo<GoodsOrder> queryPageBySellerId2(int currentPage, int pageSize, Long userId) {
        PageHelper.startPage(currentPage,pageSize);
        List<GoodsOrder> goodsOrders = goodsOrderMapper.queryAllBySellerUserId2(userId);
        PageInfo<GoodsOrder> goodsOrderPageInfo = new PageInfo<>(goodsOrders);
        return goodsOrderPageInfo;
    }

    @Override
    public PageInfo<GoodsOrder> queryPageBySellerId3(int currentPage, int pageSize, Long userId) {
        PageHelper.startPage(currentPage,pageSize);
        List<GoodsOrder> goodsOrders = goodsOrderMapper.queryAllBySellerUserId3(userId);
        PageInfo<GoodsOrder> goodsOrderPageInfo = new PageInfo<>(goodsOrders);
        return goodsOrderPageInfo;
    }


    @Transactional(rollbackFor = {})
    @Override
    public boolean payOrder(GoodsOrder goodsOrder) {

        //扣余额
        int i = userInfoMapper.updateBalance(goodsOrder.getTransactionAmount(), goodsOrder.getBuyerUserId());
        if(i == 0){
            return false;
        }
        //更改订单状态 2为已支付
        goodsOrder.setStatus("2");
        boolean b = this.updateById(goodsOrder);
        if(!b){
            //抛出异常回滚数据
            throw new  RuntimeException("支付失败");
        }
        //退还保证金
        int i1 = goodsDepositMapper.RefundDeposit(goodsOrder.getBuyerUserId(), goodsOrder.getGoodsId());
        if(i1 != 2){
            throw  new RuntimeException("退还保证金失败");
        }

        Long sellerUserId = goodsOrder.getSellerUserId();
        //查询卖方邮箱
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getUserId,sellerUserId);
        lambdaQueryWrapper.select(UserInfo::getEmail);
        UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);
        emailSender.send(userInfo.getEmail(),"你好！<br/>你的商品"+goodsOrder.getGoodsName() + "卖家已付款，请在72小时内完成发货。" );
        return true;
    }
}
